Handlers and Notify in Ansible
In Ansible, handlers are a special type of task that only run when notified by other tasks. They are commonly used for actions that should occur only when there is a change in the state of a resource, optimizing playbook runs by avoiding unnecessary operations.
How Handlers Work
- Definition: Handlers are defined like regular tasks but are placed under a
handlerssection in your playbook. - Notification: A task can notify a handler when it makes a change, using the
notifykeyword. - Execution: Handlers are executed at the end of a play, after all tasks have run, and only if they have been notified.
Example
---
- name: Example Playbook
hosts: webservers
tasks:
- name: Install nginx
apt:
name: nginx
state: present
notify: Restart nginx # Notify the handler if this task changes
- name: Update nginx configuration
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart nginx # Notify the handler if this task changes
handlers:
- name: Restart nginx
service:
name: nginx
state: restarted
Breakdown of the Example
- Tasks:
- The first task installs
nginx. If it is not already installed, it will notify the handlerRestart nginx. - The second task updates the
nginxconfiguration file. If the configuration changes, it will also notify the handler.
- The first task installs
- Handlers:
- The handler
Restart nginxis defined under thehandlerssection. It restarts thenginxservice.
- The handler
- Execution Flow:
- If either the installation of
nginxor the configuration update results in a change, the handler will be called at the end of the playbook run to restart the service.
- If either the installation of
Key Points
- Handlers run only when notified, avoiding unnecessary service restarts or actions unless a change occurs.
- You can have multiple tasks notify the same handler, which will run only once, even if notified multiple times during the playbook run.
- Handlers can be useful for tasks such as restarting services, clearing caches, or performing any other action that should occur only when a certain condition is met.
Feel free to ask if you have any specific scenarios or questions about using handlers in Ansible!

Comments
Post a Comment